import numpy as np
import csv
from datetime import datetime
from time import strftime
import math

def getCurTime():
    """
    get current time
    Return value of the date string format(%Y-%m-%d %H:%M:%S)
    """
    format='%Y-%m-%d %H:%M:%S'
    sdate = None
    cdate = datetime.now()
    try:
        sdate = cdate.strftime(format)
    except:
        raise ValueError
    return sdate

def build_data_list(inputCSV):
    sKey = []
    fn = inputCSV
    f = open(inputCSV)
    #ra = csv.DictReader(file(fn), dialect="excel")
    ra = csv.DictReader(f, dialect="excel")
    
    for record in ra:
        #print record[ra.fieldnames[0]], type(record[ra.fieldnames[-1]])
        for item in ra.fieldnames:
            temp = int(float(record[item]))
            sKey.append(temp)
    sKey = np.array(sKey)
    sKey.shape=(-1,len(ra.fieldnames))
    return sKey

def distance(x1, y1, x2, y2):
    #print x1, y1, x2, y2
    x1 = float(x1)
    y1 = float(y1)
    x2 = float(x2)
    y2 = float(y2)
    temp = int(math.pow((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2), 0.5))
    return temp
    


#--------------------------------------------------------------------------
#MAIN

if __name__ == "__main__":
    print '===================================================='
    print "begin at " + getCurTime()

    filepath = 'C:/_DATA/migration_census_2000/'
    dataCSV = filepath + 'census_county_migration_format_dist.csv'
    data = build_data_list(dataCSV) #dist	OrigId	destId	flowVol

    
    #excludelist = [2,15]    #2: Alaska, 15: Hawaii

    centroidcsv = filepath + 'census_county_centroid.csv'
    centroid = build_data_list(centroidcsv) #[fid, fips, x, y]

    grossflow = np.zeros((len(centroid), 2))
    for item in data:
        grossflow[item[2],0] += item[3]
        grossflow[item[1],1] += item[3]

    popcsv = filepath + 'census_county_pop.csv'
    pop = build_data_list(popcsv)

    graphdistcsv = filepath + 'cnty_graphdistance.csv'
    graphdist = build_data_list(graphdistcsv)

    regressiondata = []
    for item in data:
        oid = item[1]
        did = item[2]
        #dist = distance(county[oid,2], county[oid,3], county[did,2], county[did,3])
        dist = distance(centroid[oid,0], centroid[oid,1], centroid[did,0], centroid[did,1])
        regressiondata.append([dist, graphdist[oid,did], grossflow[oid,1], grossflow[did,0], pop[oid,-2], pop[did,-2], item[-1]])
    regressiondata = np.array(regressiondata)
    regressiondata.shape = (-1, 7)
    #metroCountyCSV = filepath + 'metropolitan/metro_county_list.csv'
    #metroCounty = build_data_list(metroCountyCSV)

    #countyunique = np.unique(formatdata[:,1])
    #print countyunique, len(countyunique)
    headerstr = 'oid,did,vol,evol'
    #np.savetxt(filepath + 'dataformat.csv', formatdata, delimiter=',', header = headerstr, fmt = '%s')

    headerstr = 'grossin,grossout'
    np.savetxt(filepath + 'grossflow.csv', grossflow, delimiter=',', header = headerstr, fmt = '%s')

    headerstr = 'dist,graphdist,grossout,grossin,popout,popin,vol'
    np.savetxt(filepath + 'regressiondata1.csv', regressiondata, delimiter=',', header = headerstr, fmt = '%s')


    '''
    metro_id = {}

    i = 0    
    for item in metro:
        metro_id[int(item)] = i
        i += 1

    county_id = {}

    for item in metroCounty:
        county_id[int(item[0])] = metro_id[int(item[1])]

    #print metro
    print metro_id

    
    for item in data:
        if int(item[1]) in county_id:
            item[-1] = county_id[int(item[1])]
        else:
            item[-1] = 999

    #print max(data[:,-1])



    #np.savetxt(filepath + 'metropolitan/census_county_pop_metro.csv', data, delimiter=',', fmt = '%s')
    '''